package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;


/**
 * ControllerAdvice注解:
 *   1.标识该类为全局异常处理器;
 *   2.当控制器抛出异常时,框架优先检查是否定义了全局异常处理器;
 * RestControllerAdvice注解:
 *   1.组合注解,相当于:ControllerAdvice + ResponseBody注解;
 *   2.添加该注解后,所有的异常处理方法上无需再添加 @ResponseBody 注解;
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
//    @ResponseBody
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        String data = ex.getMessage();
        log.error("IllegalArgumentException = "+data);
        return JsonResult.fail(data);
    }
//    @ExceptionHandler
//    public JsonResult doHandleThrowable(Throwable ex){
//        String data = ex.getMessage();
//        log.error("doHandleThrowable = "+data);
//        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
//    }
    @ExceptionHandler
    public JsonResult dohandleRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
        log.error("RuntimeException = "+data);
        return JsonResult.fail(data);

    }

    /**
     * 异常处理方法 ：处理封装类[pojo]参数合法性校验失败的场景
     */
    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException
    (MethodArgumentNotValidException ex){
        //封装类参数异常提示消息:ex.getFieldError().getDefaultMessage();
        String data = ex.getFieldError().getDefaultMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);

    }

    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException
            (ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException = "+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);

    }



















}
